package filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class PostValidatorFilter
 */
public class PostValidationFilter implements Filter {

    /**
     * Default constructor. 
     */
    public PostValidationFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		
		//only do with post
		if (req.getMethod().equals("POST"))
		{
			String postTitle = req.getParameter("postTitle");
			String postContent = req.getParameter("postContent");
			boolean isError = false;
			String errorMsg = "";
			
			if (postContent == null || postContent.equals("") || postContent.equals("<p><br></p>") || postContent.equals("<p></p>"))
			{
				isError = true;
				errorMsg += "Post content is required\n";
			}
			
			if (postTitle == null || postTitle.equals(""))
			{
				isError = true;
				errorMsg += "Post title is required\n";
			}
			
			if (isError) //error
			{
				//set the error
				session.setAttribute("ReturnStatus", errorMsg);
				
				//redirect
				res.sendRedirect(req.getServletPath().substring(1) + "?postID=" + req.getParameter("postID"));
			}
			else
			{
				chain.doFilter(request, response);
			}
		}
		else
		{
			// pass the request along the filter chain
			chain.doFilter(request, response);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
